// 模态框系统 Store

import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Modal, ModalOptions } from '@/types/modal'

export const useModalStore = defineStore('modal', () => {
  const modals = ref<Modal[]>([])

  const openModal = (options: ModalOptions): string => {
    const id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
    
    const modal: Modal = {
      id,
      title: options.title,
      icon: options.icon,
      size: options.size || 'medium',
      fullscreen: options.fullscreen || false,
      closable: options.closable !== false, // 默认可关闭
      closeOnBackdrop: options.closeOnBackdrop !== false, // 默认点击背景关闭
      blur: options.blur !== false, // 默认背景模糊
      showHeader: options.showHeader !== false, // 默认显示头部
      resizable: options.resizable || false,
      
      component: options.component,
      props: options.props || {},
      content: options.content,
      message: options.message,
      
      actions: options.actions || [],
      headerActions: options.headerActions || [],
      
      style: options.style || {},
      
      createdAt: Date.now()
    }

    modals.value.push(modal)
    return id
  }

  const closeModal = (id: string) => {
    const index = modals.value.findIndex(m => m.id === id)
    if (index > -1) {
      modals.value.splice(index, 1)
    }
  }

  const updateModal = (id: string, updates: Partial<Modal>) => {
    const modal = modals.value.find(m => m.id === id)
    if (modal) {
      Object.assign(modal, updates)
    }
  }

  const clearModals = () => {
    modals.value = []
  }

  // 便捷方法
  const confirm = (
    title: string, 
    message: string, 
    onConfirm?: () => void | Promise<void>,
    onCancel?: () => void
  ): string => {
    return openModal({
      title,
      message,
      size: 'small',
      actions: [
        {
          id: 'cancel',
          label: '取消',
          type: 'secondary',
          handler: onCancel
        },
        {
          id: 'confirm',
          label: '确认',
          type: 'primary',
          handler: onConfirm
        }
      ]
    })
  }

  const alert = (title: string, message: string, onClose?: () => void): string => {
    return openModal({
      title,
      message,
      size: 'small',
      actions: [
        {
          id: 'ok',
          label: '确定',
          type: 'primary',
          handler: onClose
        }
      ]
    })
  }

  const prompt = (
    title: string, 
    message: string, 
    defaultValue: string = '',
    onConfirm?: (value: string) => void | Promise<void>,
    onCancel?: () => void
  ): string => {
    // 这里需要一个专门的 PromptModal 组件
    return openModal({
      title,
      size: 'small',
      component: 'PromptModal', // 需要创建这个组件
      props: {
        message,
        defaultValue,
        onConfirm,
        onCancel
      }
    })
  }

  return {
    modals,
    openModal,
    closeModal,
    updateModal,
    clearModals,
    confirm,
    alert,
    prompt
  }
})